import { Component, OnInit, Input, Injector } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ModalComponentBase } from '@shared/component-base';
import { OrganizationUnits } from 'entities/organizationunits';
import { OrganizationUnitsServiceProxy } from 'services/organizationunits/organizationunits.service';
import { finalize } from 'rxjs/operators';

@Component({
  selector: 'app-create-or-update-organizationunits',
  templateUrl: './create-or-update-organizationunits.component.html',
  styles: [],
  providers: [OrganizationUnitsServiceProxy],
})

export class CreateOrUpdateOrganizationUnitsComponent extends ModalComponentBase
  implements OnInit {
  @Input() id?: number;
  @Input() parentId?: number;
  @Input() displayName?: string;

  title: string;
  form: FormGroup;
  organizationUnits: OrganizationUnits = new OrganizationUnits();
  constructor(injector: Injector, private organizationunitsService: OrganizationUnitsServiceProxy, private fb: FormBuilder,) {
    super(injector);
  }

  ngOnInit() {
    this.form = this.fb.group({
      displayName: [
        null,
        Validators.compose([Validators.required, Validators.maxLength(30)]),
      ]
    });
    if (this.id) {
      //先获取当前数据
      this.getData();
      this.title = '编辑组织单位';
    } else {
      this.organizationUnits.parentId = this.parentId;
      if (this.organizationUnits.parentId)
        this.title = '添加子组织';
      else
        this.title = '添加根组织';
    }
  }

  getData() {
    this.organizationunitsService.GetByIdAsync(this.id).subscribe(result => {
      this.organizationUnits = result;
    });
  }


  save(): void {
    if (!this.organizationUnits.id) {
      this.createUnit();
    } else {
      this.updateUnit();
    }
  }

  createUnit() {
    //this.saving = true;
    this.organizationunitsService.createOrganizationUnit(this.organizationUnits)
      .pipe(finalize(() => this.saving = false))
      .subscribe((result: OrganizationUnits) => {
        //this.notify.info(this.l('SavedSuccessfully'));
        this.notify.success('保存成功！');
        this.success();
      });
  }
  updateUnit() {
    //this.saving = true;
    this.organizationunitsService.updateOrganizationUnit(this.organizationUnits)
      .pipe(finalize(() => this.saving = false))
      .subscribe((result: OrganizationUnits) => {
        //this.notify.info(this.l('SavedSuccessfully'));
        this.notify.success('保存成功！');
        this.success();
      });
  }


}
